package com.adam.example.aggregation.bucket;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.*;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.util.DateTime;
import com.adam.example.ElasticsearchClientHolder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalField;
import java.util.Date;
import java.util.List;

public class DateHistogramAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchResponse<Void> searchResponse = elasticsearchClient.search(builder -> builder
                        .index("test_books")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .dateHistogram(dateHistogramAggregationBuilder -> dateHistogramAggregationBuilder
                                        .field("publish_time").calendarInterval(CalendarInterval.Year)
                                )
                        )
                , Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        DateHistogramAggregate dateHistogramAggregate = aggregate.dateHistogram();
        Buckets<DateHistogramBucket> buckets = dateHistogramAggregate.buckets();
        List<DateHistogramBucket> bucketList = buckets.array();
        for(DateHistogramBucket bucket: bucketList) {
            DateTime dateTime = bucket.key();
            int year = dateTime.toZonedDateTime().getYear();
            System.out.println(year + ":" + bucket.docCount());
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
